<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>AngulaJS 服务</title>
		<style>
			body{
			  font-family: 'microsoft yahei',Arial,sans-serif;
			}
			
			h1{
			  font-weight:500;
			  font-size:24px;
			}
			
			p{
			  margin:30px 0 30px;
			}

		</style>
	</head>

	<body>
		<h1>AngularJS 自定义指令</h1>
		<hr />
		
		<div ng-app="mainApp" ng-controller="StudentController">
			<!--自定义元素指令-->
			<p><student name="Terry"></student></p>
			<p><student name="Paul"></student></p>
		</div>
		
		<script src="http://cdn.gbtags.com/angular.js/1.2.20/angular.min.js"></script>
		<script>
			var mainApp = angular.module('mainApp', []);
			
			//创建一个指令，第一次参数是匹配的html元素，这里寻找student标签
			//这个指令在找到匹配的student元素时自动激活
			mainApp.directive('student', function(){
				//定义自定义元素
				var directive = {};
				 //指定类型，这里为“E”，即“Element”，元素指令
				directive.restrict = 'E';
				 //替换元素的模板文字
				directive.template = '学生：<b>{{student.name}}</b>，编号：<b>{{student.rollno}}</b>';
				//scope用来基于规则区别每一个student元素
				directive.scope = {
					student : '=name'
				};
				//初始化应用时调用编译，AngularJS在HTML页面加载时只调用一次.
				directive.compile = function(element, attributes){
					element.css('border', '1px solid #ccc');
					element.css('padding', '10px');
					 //linkFunction将连接每一个元素和scope，来获取指定数据
					var linkFunction = function($scope, element, attributes){
						element.html('学生：<b>' + $scope.student.name + '</b>，编号：<b>' + $scope.student.rollno + '</b><br/>');
						element.css('color', 'orange');
					};
					
					return linkFunction;
				};
				
				return directive;
			});
			
			// 定义控制器来更新指令的scope，我们使用名字属性对应值作为scope的子对象：
			mainApp.controller('StudentController', function($scope){
				$scope.Terry = [];
				$scope.Terry.name = "Terry lee";
				$scope.Terry.rollno = 1;
				$scope.Paul = [];
				$scope.Paul.name = "Paul lee";
				$scope.Paul.rollno = 2;
			});
			
		</script>
	</body>

</html>